<template>
  <div class="quality-inspection">
    <div class="page-header">
      <h2>维修质量检查</h2>
      <Button type="primary" @click="showAddModal = true">
        <IconifyIcon icon="ant-design:plus-outlined" />
        新建检查
      </Button>
    </div>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="总检查数"
          :value="statistics.totalInspections"
          :change="statistics.totalChange"
          icon="ant-design:audit-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="通过率"
          :value="statistics.passRate"
          :change="statistics.passRateChange"
          icon="ant-design:check-circle-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="平均评分"
          :value="statistics.averageScore"
          :change="statistics.scoreChange"
          icon="ant-design:star-outlined"
          color="#faad14"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="待检查"
          :value="statistics.pendingInspections"
          :change="statistics.pendingChange"
          icon="ant-design:clock-circle-outlined"
          color="#faad14"
        />
      </Col>
    </Row>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form layout="inline" :model="searchForm" class="search-form">
        <FormItem label="工单号">
          <Input
            v-model:value="searchForm.workOrderNumber"
            placeholder="请输入工单号"
            allow-clear
          />
        </FormItem>
        <FormItem label="检查人员">
          <Input
            v-model:value="searchForm.inspector"
            placeholder="请输入检查人员"
            allow-clear
          />
        </FormItem>
        <FormItem label="检查结果">
          <Select
            v-model:value="searchForm.result"
            placeholder="请选择结果"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="pass">通过</SelectOption>
            <SelectOption value="fail">不通过</SelectOption>
            <SelectOption value="pending">待检查</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="检查日期">
          <DatePicker
            v-model:value="searchForm.inspectionDate"
            placeholder="选择日期"
            style="width: 150px"
          />
        </FormItem>
        <FormItem>
          <Space>
            <Button type="primary" @click="handleSearch">
              <IconifyIcon icon="ant-design:search-outlined" />
              搜索
            </Button>
            <Button @click="handleReset">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置
            </Button>
          </Space>
        </FormItem>
      </Form>
    </Card>

    <!-- 质量趋势图 -->
    <Card title="质量趋势" class="chart-card">
      <div class="chart-container">
        <div class="chart-placeholder">
          <IconifyIcon
            icon="ant-design:bar-chart-outlined"
            class="chart-icon"
          />
          <p>质量评分趋势图表</p>
          <p class="chart-desc">显示最近30天的质量评分变化趋势</p>
        </div>
      </div>
    </Card>

    <!-- 检查记录表格 -->
    <Card class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredInspections"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'workOrderNumber'">
            <Button type="link" @click="viewWorkOrderDetail(record)">
              {{ record.workOrderNumber }}
            </Button>
          </template>
          <template v-else-if="column.key === 'result'">
            <Tag :color="getResultColor(record.result)">
              {{ getResultText(record.result) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'score'">
            <div class="score-info">
              <span class="score-value">{{ record.score }}</span>
              <span class="score-max">/100</span>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                查看详情
              </Button>
              <Button type="link" size="small" @click="editInspection(record)">
                编辑
              </Button>
              <Button
                v-if="record.result === 'pending'"
                type="link"
                size="small"
                @click="conductInspection(record)"
              >
                开始检查
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 新建检查弹窗 -->
    <Modal
      v-model:open="showAddModal"
      title="新建质量检查"
      width="700px"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <Form ref="formRef" :model="form" :rules="rules" layout="vertical">
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="工单号" name="workOrderNumber">
              <Select
                v-model:value="form.workOrderNumber"
                placeholder="选择工单"
                show-search
              >
                <SelectOption
                  v-for="workOrder in availableWorkOrders"
                  :key="workOrder.id"
                  :value="workOrder.workOrderNumber"
                >
                  {{ workOrder.workOrderNumber }} - {{ workOrder.roomNumber }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="检查人员" name="inspector">
              <Select v-model:value="form.inspector" placeholder="选择检查人员">
                <SelectOption value="张主管">张主管</SelectOption>
                <SelectOption value="李经理">李经理</SelectOption>
                <SelectOption value="王师傅">王师傅</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="检查日期" name="inspectionDate">
              <DatePicker
                v-model:value="form.inspectionDate"
                placeholder="选择检查日期"
                style="width: 100%"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="检查类型" name="inspectionType">
              <Select
                v-model:value="form.inspectionType"
                placeholder="选择检查类型"
              >
                <SelectOption value="routine">常规检查</SelectOption>
                <SelectOption value="special">专项检查</SelectOption>
                <SelectOption value="random">随机抽查</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="检查说明" name="description">
          <Textarea
            v-model:value="form.description"
            placeholder="请输入检查说明"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 检查详情弹窗 -->
    <Modal
      v-model:open="showDetailModal"
      title="检查详情"
      width="800px"
      :footer="null"
    >
      <Descriptions :column="2" bordered>
        <DescriptionsItem label="工单号">
          {{ selectedInspection?.workOrderNumber }}
        </DescriptionsItem>
        <DescriptionsItem label="房间号">
          {{ selectedInspection?.roomNumber }}
        </DescriptionsItem>
        <DescriptionsItem label="检查人员">
          {{ selectedInspection?.inspector }}
        </DescriptionsItem>
        <DescriptionsItem label="检查日期">
          {{ selectedInspection?.inspectionDate }}
        </DescriptionsItem>
        <DescriptionsItem label="检查结果">
          <Tag :color="getResultColor(selectedInspection?.result)">
            {{ getResultText(selectedInspection?.result) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="评分">
          {{ selectedInspection?.score }}/100
        </DescriptionsItem>
        <DescriptionsItem label="检查项目" :span="2">
          <div class="inspection-items">
            <div
              v-for="item in selectedInspection?.items"
              :key="item.name"
              class="inspection-item"
            >
              <span class="item-name">{{ item.name }}</span>
              <Tag :color="item.passed ? 'green' : 'red'">
                {{ item.passed ? '通过' : '不通过' }}
              </Tag>
              <span class="item-score">{{ item.score }}分</span>
            </div>
          </div>
        </DescriptionsItem>
        <DescriptionsItem label="检查意见" :span="2">
          {{ selectedInspection?.comments || '无' }}
        </DescriptionsItem>
        <DescriptionsItem label="改进建议" :span="2">
          {{ selectedInspection?.suggestions || '无' }}
        </DescriptionsItem>
      </Descriptions>
    </Modal>

    <!-- 执行检查弹窗 -->
    <Modal
      v-model:open="showConductModal"
      title="执行质量检查"
      width="800px"
      @ok="handleConductSave"
      @cancel="showConductModal = false"
    >
      <Form
        ref="conductFormRef"
        :model="conductForm"
        :rules="conductRules"
        layout="vertical"
      >
        <FormItem label="检查项目" name="items">
          <div class="inspection-items-form">
            <div
              v-for="item in inspectionItems"
              :key="item.id"
              class="inspection-item-form"
            >
              <div class="item-header">
                <span class="item-name">{{ item.name }}</span>
                <span class="item-max-score">({{ item.maxScore }}分)</span>
              </div>
              <div class="item-content">
                <Checkbox v-model:checked="item.passed">通过</Checkbox>
                <Input
                  v-model:value="item.score"
                  type="number"
                  :min="0"
                  :max="item.maxScore"
                  placeholder="评分"
                  style="width: 80px"
                />
                <span class="score-unit">分</span>
              </div>
              <Textarea
                v-model:value="item.comment"
                placeholder="检查意见"
                :rows="2"
              />
            </div>
          </div>
        </FormItem>
        <FormItem label="总体评分" name="totalScore">
          <Input
            v-model:value="conductForm.totalScore"
            type="number"
            :min="0"
            :max="100"
            placeholder="总体评分"
          />
        </FormItem>
        <FormItem label="检查结果" name="result">
          <Radio.Group v-model:value="conductForm.result">
            <Radio value="pass">通过</Radio>
            <Radio value="fail">不通过</Radio>
          </Radio.Group>
        </FormItem>
        <FormItem label="检查意见" name="comments">
          <Textarea
            v-model:value="conductForm.comments"
            placeholder="总体检查意见"
            :rows="3"
          />
        </FormItem>
        <FormItem label="改进建议" name="suggestions">
          <Textarea
            v-model:value="conductForm.suggestions"
            placeholder="改进建议"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import StatisticsCard from '#/components/hotel/StatisticsCard.vue';
import {
  Button,
  Card,
  Checkbox,
  Col,
  DatePicker,
  Descriptions,
  DescriptionsItem,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Radio,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';
import dayjs from 'dayjs';

// 状态管理
const loading = ref(false);
const showAddModal = ref(false);
const showDetailModal = ref(false);
const showConductModal = ref(false);
const isEdit = ref(false);
const selectedInspection = ref(null);

// 表单引用
const formRef = ref();
const conductFormRef = ref();

// 统计数据
const statistics = reactive({
  totalInspections: 89,
  totalChange: 5,
  passRate: 92.5,
  passRateChange: 2.1,
  averageScore: 87.6,
  scoreChange: 1.2,
  pendingInspections: 12,
  pendingChange: -3,
});

// 搜索表单
const searchForm = reactive({
  workOrderNumber: '',
  inspector: '',
  result: '',
  inspectionDate: null,
});

// 检查表单
const form = reactive({
  workOrderNumber: '',
  inspector: '',
  inspectionDate: null,
  inspectionType: 'routine',
  description: '',
});

// 执行检查表单
const conductForm = reactive({
  totalScore: 0,
  result: 'pass',
  comments: '',
  suggestions: '',
});

// 表单验证规则
const rules = {
  workOrderNumber: [{ required: true, message: '请选择工单' }],
  inspector: [{ required: true, message: '请选择检查人员' }],
  inspectionDate: [{ required: true, message: '请选择检查日期' }],
  inspectionType: [{ required: true, message: '请选择检查类型' }],
};

const conductRules = {
  totalScore: [{ required: true, message: '请输入总体评分' }],
  result: [{ required: true, message: '请选择检查结果' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 可用工单
const availableWorkOrders = ref([
  { id: 1, workOrderNumber: 'WO-2024-001', roomNumber: '101' },
  { id: 2, workOrderNumber: 'WO-2024-002', roomNumber: '205' },
  { id: 3, workOrderNumber: 'WO-2024-003', roomNumber: '302' },
  { id: 4, workOrderNumber: 'WO-2024-004', roomNumber: '401' },
]);

// 检查项目
const inspectionItems = ref([
  {
    id: 1,
    name: '维修质量',
    maxScore: 30,
    passed: true,
    score: 28,
    comment: '维修质量良好，符合标准',
  },
  {
    id: 2,
    name: '安全标准',
    maxScore: 25,
    passed: true,
    score: 24,
    comment: '安全措施到位',
  },
  {
    id: 3,
    name: '现场清洁',
    maxScore: 20,
    passed: true,
    score: 18,
    comment: '现场清洁度良好',
  },
  {
    id: 4,
    name: '文档完整',
    maxScore: 15,
    passed: true,
    score: 14,
    comment: '维修记录完整',
  },
  {
    id: 5,
    name: '客户满意度',
    maxScore: 10,
    passed: true,
    score: 9,
    comment: '客户对维修结果满意',
  },
]);

// 检查记录数据
const inspections = ref([
  {
    id: 1,
    workOrderNumber: 'WO-2024-001',
    roomNumber: '101',
    inspector: '张主管',
    inspectionDate: '2024-01-15',
    result: 'pass',
    score: 92,
    items: [
      { name: '维修质量', passed: true, score: 28 },
      { name: '安全标准', passed: true, score: 24 },
      { name: '现场清洁', passed: true, score: 18 },
      { name: '文档完整', passed: true, score: 14 },
      { name: '客户满意度', passed: true, score: 8 },
    ],
    comments: '整体维修质量良好，符合标准要求',
    suggestions: '建议加强现场清洁管理',
  },
  {
    id: 2,
    workOrderNumber: 'WO-2024-002',
    roomNumber: '205',
    inspector: '李经理',
    inspectionDate: '2024-01-14',
    result: 'pass',
    score: 88,
    items: [
      { name: '维修质量', passed: true, score: 26 },
      { name: '安全标准', passed: true, score: 23 },
      { name: '现场清洁', passed: true, score: 17 },
      { name: '文档完整', passed: true, score: 13 },
      { name: '客户满意度', passed: true, score: 9 },
    ],
    comments: '维修工作完成度较高',
    suggestions: '无',
  },
  {
    id: 3,
    workOrderNumber: 'WO-2024-003',
    roomNumber: '302',
    inspector: '王师傅',
    inspectionDate: '2024-01-13',
    result: 'fail',
    score: 65,
    items: [
      { name: '维修质量', passed: false, score: 20 },
      { name: '安全标准', passed: true, score: 22 },
      { name: '现场清洁', passed: false, score: 12 },
      { name: '文档完整', passed: true, score: 11 },
      { name: '客户满意度', passed: false, score: 0 },
    ],
    comments: '维修质量不达标，需要重新维修',
    suggestions: '加强维修人员培训，提高维修质量',
  },
  {
    id: 4,
    workOrderNumber: 'WO-2024-004',
    roomNumber: '401',
    inspector: '张主管',
    inspectionDate: '2024-01-12',
    result: 'pending',
    score: 0,
    items: [],
    comments: '',
    suggestions: '',
  },
]);

// 表格列定义
const columns = [
  {
    title: '工单号',
    dataIndex: 'workOrderNumber',
    key: 'workOrderNumber',
    width: 120,
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 80,
  },
  {
    title: '检查人员',
    dataIndex: 'inspector',
    key: 'inspector',
    width: 100,
  },
  {
    title: '检查日期',
    dataIndex: 'inspectionDate',
    key: 'inspectionDate',
    width: 120,
  },
  {
    title: '检查结果',
    dataIndex: 'result',
    key: 'result',
    width: 100,
  },
  {
    title: '评分',
    dataIndex: 'score',
    key: 'score',
    width: 80,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 过滤后的检查数据
const filteredInspections = computed(() => {
  let result = inspections.value;

  if (searchForm.workOrderNumber) {
    result = result.filter((item) =>
      item.workOrderNumber
        .toLowerCase()
        .includes(searchForm.workOrderNumber.toLowerCase()),
    );
  }

  if (searchForm.inspector) {
    result = result.filter((item) =>
      item.inspector.toLowerCase().includes(searchForm.inspector.toLowerCase()),
    );
  }

  if (searchForm.result) {
    result = result.filter((item) => item.result === searchForm.result);
  }

  if (searchForm.inspectionDate) {
    result = result.filter(
      (item) => item.inspectionDate === searchForm.inspectionDate,
    );
  }

  return result;
});

// 结果相关函数
const getResultColor = (result: string) => {
  const colors: Record<string, string> = {
    pass: 'green',
    fail: 'red',
    pending: 'orange',
  };
  return colors[result] || 'default';
};

const getResultText = (result: string) => {
  const texts: Record<string, string> = {
    pass: '通过',
    fail: '不通过',
    pending: '待检查',
  };
  return texts[result] || result;
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

const handleReset = () => {
  Object.assign(searchForm, {
    workOrderNumber: '',
    inspector: '',
    result: '',
    inspectionDate: null,
  });
  pagination.current = 1;
  message.success('重置完成');
};

const handleSave = async () => {
  try {
    await formRef.value.validate();
    if (isEdit.value) {
      message.success('检查记录更新成功');
    } else {
      message.success('检查记录创建成功');
    }
    showAddModal.value = false;
    resetForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  showAddModal.value = false;
  resetForm();
};

const handleConductSave = async () => {
  try {
    await conductFormRef.value.validate();
    message.success('检查完成');
    showConductModal.value = false;
    resetConductForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const viewDetail = (record: any) => {
  selectedInspection.value = record;
  showDetailModal.value = true;
};

const editInspection = (record: any) => {
  isEdit.value = true;
  Object.assign(form, record);
  showAddModal.value = true;
};

const conductInspection = (record: any) => {
  selectedInspection.value = record;
  showConductModal.value = true;
};

const viewWorkOrderDetail = (record: any) => {
  message.info(`查看工单详情: ${record.workOrderNumber}`);
};

const resetForm = () => {
  Object.assign(form, {
    workOrderNumber: '',
    inspector: '',
    inspectionDate: null,
    inspectionType: 'routine',
    description: '',
  });
  isEdit.value = false;
};

const resetConductForm = () => {
  Object.assign(conductForm, {
    totalScore: 0,
    result: 'pass',
    comments: '',
    suggestions: '',
  });
};

onMounted(() => {
  // 初始化数据
  pagination.total = inspections.value.length;
});
</script>

<style scoped>
.quality-inspection {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.chart-card {
  margin-bottom: 16px;
}

.chart-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.chart-placeholder {
  color: #999;
  text-align: center;
}

.chart-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.chart-desc {
  margin-top: 8px;
  font-size: 14px;
}

.table-card {
  margin-bottom: 16px;
}

.score-info {
  display: flex;
  gap: 4px;
  align-items: center;
}

.score-value {
  font-weight: 500;
  color: #1890ff;
}

.score-max {
  color: #999;
}

.inspection-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.inspection-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.item-name {
  min-width: 80px;
  font-weight: 500;
}

.item-score {
  font-weight: 500;
  color: #1890ff;
}

.inspection-items-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.inspection-item-form {
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
}

.item-header {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 8px;
}

.item-name {
  font-weight: 500;
}

.item-max-score {
  font-size: 12px;
  color: #999;
}

.item-content {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 8px;
}

.score-unit {
  color: #999;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}

:deep(.ant-descriptions-item-label) {
  width: 120px;
  font-weight: 500;
}
</style>
